package com.amiu.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.amiu.shiro.PasswordHashHelper;
import com.amiu.shiro.db.user.User;
import com.amiu.shiro.db.user.UserDao;
import com.amiu.util.Result;
import com.amiu.util.ResultUtil;

@RestController
public class UserController {
	@Autowired PasswordHashHelper passwordHelper;
	@Autowired UserDao userDao;
	
	@RequestMapping("/regist")
	public Result regist(@RequestBody User registAcount){
		String username = registAcount.getUsername();
		String password = registAcount.getPassword();
		
		String salt = username;
		String passwordWithSalt = passwordHelper.encryptPassword(password, salt);
		//这只是测试的时候用的，为了不忘记加盐后的密码。
		String description = "pwd:"+password;
		
		registAcount.setPassword(passwordWithSalt);//将明文密码替换为加盐密码
		registAcount.setPassword_salt(salt);
		registAcount.setDescription(description);
		
		System.out.println(registAcount.toString());
		
		if(userDao.findByName(username) != null)
			return new ResultUtil().renderFail("该用户名已被注册！");
		
		userDao.createUserReturnId(registAcount);
		long id = -1;
		try {
			id = registAcount.getId();
		} catch (Exception e) {
			return new ResultUtil().renderFail("申请新账户失败");
		}
		
		return new ResultUtil().renderSuccess("regist success", id);
	}
}
